<template>
  <!-- 新增/修改 -->
  <el-dialog
    v-model="dialogVisible"
    :title="formData.id === undefined ? '新增用户' : '修改用户'"
    @closed="closedDialog"
    width="50%"
    :close-on-click-modal="false"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      label-position="right"
      v-loading="formLoading"
    >
      <el-form-item label="用户账户" prop="account">
        <el-input v-model="formData.account" placeholder="请输入用户账户" />
      </el-form-item>
      <el-form-item
        v-if="formData.id === undefined"
        label="用户密码"
        prop="password"
      >
        <el-input
          v-model="formData.password"
          placeholder="请输入用户密码"
          show-password
        />
      </el-form-item>
      <el-form-item label="用户姓名" prop="userName">
        <el-input v-model="formData.userName" placeholder="请输入用户姓名" />
      </el-form-item>
      <el-form-item label="租户" prop="tenantId">
        <el-input v-model="formData.tenantId" placeholder="请输入用户租户id" />
        <!-- <TenantSearch
            v-if="dialogFormVisible"
            :tenantId="formData.tenantId"
            @onChange="tenantChange"
          /> -->
      </el-form-item>
      <el-form-item label="用户性别" prop="userSex">
        <el-select v-model="formData.userSex" placeholder="请选择用户性别">
          <el-option
            v-for="item in SEX_OPTIONS"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="用户手机号" prop="mobilePhone">
        <el-input
          v-model="formData.mobilePhone"
          placeholder="请输入用户手机号"
        />
      </el-form-item>
      <el-form-item label="用户邮箱" prop="userEmail">
        <el-input v-model="formData.userEmail" placeholder="请输入用户邮箱" />
      </el-form-item>
      <el-form-item label="是否禁用" prop="isDisabled">
        <el-select v-model="formData.isDisabled" placeholder="请选择是否禁用">
          <el-option
            v-for="item in DISABLED_OPTIONS"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="用户说明" prop="description">
        <el-input
          type="textarea"
          v-model="formData.description"
          :rows="5"
          maxlength="500"
          show-word-limit
          placeholder="请输入用户说明"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="closedDialog">取消</el-button>
      <el-button
        type="primary"
        @click="handleCreateOrUpdate"
        :loading="loading"
      >
        确认
      </el-button>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, onBeforeMount } from "vue";
import UserAPI, { type UserVO } from "@/api/system/base/user";
import { type FormInstance, type FormRules } from "element-plus";
import { cloneDeep } from "lodash-es";
import { SEX_OPTIONS, DISABLED_OPTIONS } from "@/enums/GlobalConst";

/**
 * 编辑用户详情页面
 */
defineOptions({
  name: "EditUserDetailsDialog",
});
const props = defineProps({
  userId: {
    type: String,
    required: false,
  },
  closedDialog: {
    type: Function,
    required: true,
  },
});

/** 表单初始化 */
const DEFAULT_FORM_DATA: UserVO = {
  id: props.userId,
  account: undefined,
  password: undefined,
  userName: undefined,
  userSex: 0,
  isDisabled: 0,
  mobilePhone: undefined,
  userEmail: undefined,
  description: undefined,
  tenantId: undefined,
};
/** 表单对象 */
const formData = ref<UserVO>(cloneDeep(DEFAULT_FORM_DATA));
const formRef = ref<FormInstance | null>(null);
/** 表单校验格式 */
const formRules: FormRules<any> = {
  account: [
    { required: true, message: "请输入用户账户", trigger: "blur" },
    { min: 3, max: 64, message: "长度在 3 至 64 以内个字符", trigger: "blur" },
  ],
  password: [
    { required: true, message: "请输入用户密码", trigger: "blur" },
    { min: 7, max: 32, message: "长度在 7 至 32以内个字符", trigger: "blur" },
  ],
  userName: [
    { required: true, message: "请输入用户姓名", trigger: "blur" },
    { min: 1, max: 128, message: "长度在64以内个字符", trigger: "blur" },
  ],
  mobilePhone: [
    { required: false, message: "请输入用户手机号", trigger: "blur" },
    { min: 1, max: 16, message: "长度在16以内个字符", trigger: "blur" },
  ],
  userEmail: [
    { required: false, message: "请输入用户邮箱", trigger: "blur" },
    { min: 1, max: 64, message: "长度在64以内个字符", trigger: "blur" },
  ],
  description: [
    { required: false, message: "请输入用户说明", trigger: "blur" },
    { min: 1, max: 500, message: "长度在500以内个字符", trigger: "blur" },
  ],
  tenantId: [{ required: true, message: "请输入租户id", trigger: "blur" }],
};

const dialogVisible = ref<boolean>(true);
const loading = ref<boolean>(false);
const formLoading = ref<boolean>(false);

/** 新增或者更新 */
const handleCreateOrUpdate = () => {
  formRef.value?.validate((valid: boolean, fields) => {
    if (!valid) return console.error("表单校验不通过", fields);

    loading.value = true;
    if (formData.value.id === undefined) {
      // 新增
      UserAPI.addBaseUserApi(formData.value)
        .then(() => {
          ElMessage.success("操作成功");
        })
        .finally(() => {
          loading.value = false;
          props.closedDialog(true);
        });
    } else {
      // 更新
      UserAPI.putBaseUserApi(formData.value.id, formData.value)
        .then(() => {
          ElMessage.success("操作成功");
        })
        .finally(() => {
          loading.value = false;
          props.closedDialog(true);
        });
    }
  });
};

/** 关闭弹窗 */
const closedDialog = () => {
  props.closedDialog(false);
};

/** 页面渲染完成后初始化 */
onBeforeMount(async () => {
  if (props.userId) {
    formLoading.value = true;
    UserAPI.getBaseUserByUserIdApi(props.userId)
      .then((res) => {
        const { data } = res;
        formData.value = data;
      })
      .finally(() => {
        formLoading.value = false;
      });
  }
});
</script>

<style lang="scss" scoped></style>
